/**
* @program: src
*
* @description:客户端管理
*
* @author: Mr.chen
*
* @create: 2020-11-27 15:10
**/
package models

import (
	mydb "ydd-im/service/api/tools/mysql/conn"
	"database/sql"
	"fmt"
	"time"
)

type UserClients struct {
	Id           int       `db:"id" json:"id"`
	Userid       int    `db:"userid" json:"userid"`
	ClientId     string    `db:"clientId" json:"clientId"` //创建时间
	Creattime    time.Time `db:"creattime" json:"-"`
	Creattimestr string    `json:"createat"`
}

//orm 回调
func (uc *UserClients) TableName() string {
	return TNUserClients()
}

func NewUserClients() *UserClients {
	return &UserClients{}
}
func (uc *UserClients) AddUserClients(userClients *UserClients) (insertid int64, err error) {
	sqlStr := "insert  into " + uc.TableName() + "(userid,clientId,creattime) values (?,?,?)"
	dbconn,err := mydb.DBConn("w")
	if err != nil {
		return 0, err
	}
	ret, err := dbconn.Exec(sqlStr, userClients.Userid,userClients.ClientId,userClients.Creattime)
	if err != nil {
		return 0, err
	}
	theID, err := ret.LastInsertId() // 新插入数据的id
	if err != nil {
		return 0, err
	}
	return theID, nil
}
// 根据uid查询用户信息
func (uc *UserClients) GetUserToClientIdByTouidList(touid int) (userClients []UserClients, err error) {
	userClients = []UserClients{}
	sqlStr := "select id,userid,clientId,creattime from " + uc.TableName() +"  where userid=?  and clientId !=''"
	dbconn,err := mydb.DBConn("r")
	if err != nil {
		return userClients, err
	}
	err = dbconn.Select(&userClients, sqlStr,touid)
	if err == sql.ErrNoRows { // 为空
		return userClients, nil
	}
	if err != nil {
		return userClients, err
	}
	return userClients, nil
}
// 根据相关条件删除信息
func (uc *UserClients) DeleteUserToClients(wherestr string) (err error) {
	sqlStr := fmt.Sprintf("delete from  "+ uc.TableName() + " where id in  (%s)",wherestr)  // 更新地址，并且标志在线
	dbconn,err := mydb.DBConn("w")
	if err != nil {
		return  err
	}
	ret, err := dbconn.Exec(sqlStr)
	if err != nil {
		return err
	}
	_, err = ret.RowsAffected() // 操作影响的行数
	if err != nil {
		return err
	}
	return nil
}
// 根据相关条件删除信息
func (uc *UserClients) DeleteUserToClient(clientid string) (err error) {
	sqlStr := "delete from  "+ uc.TableName() + " where clientid =  ?"  // 更新地址，并且标志在线
	dbconn,err := mydb.DBConn("w")
	if err != nil {
		return  err
	}
	ret, err := dbconn.Exec(sqlStr,clientid)
	if err != nil {
		return err
	}
	_, err = ret.RowsAffected() // 操作影响的行数
	if err != nil {
		return err
	}
	return nil
}
